package cn.edu.sdjzu.xg.eagle.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Service 工厂类，用于创建和管理 Service 实例
 */
public class ServiceFactory {
    private static final String servicePackageName = "cn.edu.sdjzu.xg.eagle.service";

    private static final Map<String, Object> serviceCache = new ConcurrentHashMap<>();

    private ServiceFactory() {
        // 私有构造函数防止实例化
    }

    /**
     * 获取指定类型的 Service 实例
     * @param serviceInterface Service 接口类
     * @param implClassName Service 实现类全名
     * @param <T> Service 接口类型
     * @return Service 实例
     * @throws RuntimeException 当创建实例失败时抛出
     */
    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> serviceInterface, String implClassName) {
        String cacheKey = serviceInterface.getName() + "_" + implClassName;

        return (T) serviceCache.computeIfAbsent(cacheKey, key -> {
            try {
                Class<?> clazz = Class.forName(servicePackageName + "." + implClassName);
                // 检查是否是单例模式的实现
                if (isSingletonImplementation(clazz)) {
                    return invokeSingletonGetInstance(clazz);
                }
                return clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("创建 Service 实例失败: " + servicePackageName + "." +implClassName, e);
            }
        });
    }

    /**
     * 检查类是否是单例实现
     */
    private static boolean isSingletonImplementation(Class<?> clazz) {
        try {
            clazz.getDeclaredMethod("getInstance");
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    /**
     * 调用单例类的 getInstance 方法
     */
    private static Object invokeSingletonGetInstance(Class<?> clazz) throws Exception {
        return clazz.getDeclaredMethod("getInstance").invoke(null);
    }
}